<script setup lang="ts">
import { ElCard, ElStatistic } from "element-plus";
import Echart from "./Echart.vue";
import { THomeChart } from "@/global";
import { computed, ref, watch } from "vue";
import { useTransition } from "@vueuse/core";

const props = defineProps<{
  data?: THomeChart["category_rank"];
}>();

const initOptions = {
  grid: {
    containLabel: true,
  },
  tooltip: {
    formatter: (params: any) => {
      return `<div><span style="color:#666">${params.name}</span>  <span style="font-weight:bold;">${params.value}</span></div>`;
    },
    padding: 10,
    borderWidth: 0,
    extraCssText: "box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);",
  },
  legend: {
    icon: "circle",
    type: "scroll",
    orient: "vertical",
    right: "10%",
    top: "center",
    bottom: 20,
    itemWidth: 8,
    formatter: (name: string) => {
      const { num = 0, total = 1 } =
        props.data?.find((e: any) => e.name == name) || {};
      return [
        `{a| ${name}}`,
        `{b| ${Math.floor((num / total) * 100)}%}`,
        `{c| ${num}}`,
      ].join(" ");
    },
    textStyle: {
      rich: {
        a: {
          display: "inline-flex",
          width: 70,
          fontWeight: "bold",
          overflow: "hidden",
        },
        b: {
          color: "#333",
          width: 50,
        },
        c: {
          color: "#666",
          width: 30,
        },
      },
    },
  },
  series: [
    {
      // name: "各品类SKU",
      type: "pie",
      radius: "82%",
      center: ["30%", "50%"],
      // label: {
      //   // show: false,
      //   // position: "inside",
      //   // alignTo: "labelLine",
      //   bleedMargin: 5,
      // },
      emphasis: {
        itemStyle: {
          shadowBlur: 5,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)",
        },
      },
    },
  ],
};

const options = ref<any>(initOptions);

watch(
  () => props.data,
  (data) => {
    options.value = {
      series: [
        {
          // name: "各品类SKU",
          data,
        },
      ],
    };
  }
);

const total = computed(() => {
  return (
    props.data?.reduce((sum, e) => {
      return sum + e.total;
    }, 0) || 0
  );
});

const renderTotal = useTransition(total, { duration: 300 });
</script>

<template>
  <ElCard>
    <template #header>
      <div class="flex items-center">
        <div class="flex-auto">
          <div class="mb-2">统计占比</div>
          <div class="text-lg font-bold">各品类SKU</div>
        </div>
        <div>
          <ElStatistic
            :value="renderTotal"
            :value-style="{ fontWeight: 'bold' }"
          />
        </div>
      </div>
    </template>

    <Echart class="h-[180px]" :options="options" />
  </ElCard>
</template>
